package dao

import "github.com/garyburd/redigo/redis"

//Redis连接池大小
var MAX_POOL_SIZE = 20
var RedisPoll chan redis.Conn
var RedisConn redis.Conn

/**
Redis
*/
func ConnRedis(network, address string) redis.Conn {
	// 缓冲机制，相当于消息队列
	if len(RedisPoll) == 0 {
		// 如果长度为0，就定义一个redis.Conn类型长度为MAX_POOL_SIZE的channel
		RedisPoll = make(chan redis.Conn, MAX_POOL_SIZE)
		go func() {
			for i := 0; i < MAX_POOL_SIZE/2; i++ {
				c, err := redis.Dial(network, address)
				if err != nil {
					panic(err)
				}
				putRedis(c)
			}
		}()
	}
	return <-RedisPoll
}

func putRedis(conn redis.Conn) {
	// 基于函数和接口间互不信任原则，这里再判断一次，养成这个好习惯
	if RedisPoll == nil {
		RedisPoll = make(chan redis.Conn, MAX_POOL_SIZE)
	}
	if len(RedisPoll) >= MAX_POOL_SIZE {
		conn.Close()
		return
	}
	RedisPoll <- conn
}

func InitRedis() {
	if RedisConn == nil {
		RedisConn = ConnRedis(RedisConf.Network, RedisConf.Address)
	}
}
